<?php

namespace Admin\Controller;

use Think\Controller;

class WeixiuController extends ComController {
    
    public function index() {
        $this->display();
    }

    public function add_book() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function edit_book() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
//        if ($admin['level'] > 0) {
//            $this->error('权限不足，无法访问');
//        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        $this->assign('book', $book);
        $this->display();
    }

    public function edit_book_chanrge() {
        $id = $_POST['id'];
        $bi = M('bookinfo');
        $gold = $_POST['gold'];
        $biid = $_POST['arr_biid'];
        $bi->where(['bid' => $id, 'id' => ['in', $biid]])->setField('gold', $gold);
        $this->success('批量修改收费成功');
    }

    public function edit_book_chanrge2() {
        $id = $_POST['id'];
        $bi = M('bookinfo');
        $gold = $_POST['gold'];
        $bi->where(['bid' => $id])->setField('gold', $gold);
        $this->success('批量修改收费成功');
    }

    public function do_add_book() {
        $data = $_POST['data'];
        if (empty($data['tid']) || empty($data['title'])) {
            $this->error('内容提交不能为空');
        }
        M()->startTrans();
        $t = M('type');
        $type = $t->where(array('id' => $data['tid']))->find();
        $w['name'] = $type['name'];
        $w['tid'] = $data['tid'];
        $w['title'] = $data['title'];
        $w['img'] = $data['img'];
        $w['content'] = $data['content'];
        $w['sex'] = $data['sex'];
        $w['state'] = $data['state'];
        $w['source'] = $data['source'];
        $w['num'] = $data['num'];
        $w['closed'] = 1; //新加的收是下架状态的
        $b = M('book');
        $i = $b->add($w);
        if (!empty($data['url'])) {//表示通过采集来的内容
            if (checkDomain($data['url'])) {
                //表示采集网上内容
            } else {
            $Bookinfo = M('Bookinfo','n_','DB_CONFIG_DEV');     
                $bid = $data['url'];
                $bookinfo = $Bookinfo->field('title2,content,number')->where(['bid' => $bid])->order('number asc')->select();
                foreach ($bookinfo as $key => $value) {
                    $bookinfo[$key]['bid'] = $i;
                    $bookinfo[$key]['time'] = time();
                }
                $ii = D('Bookinfo')->addAll($bookinfo);
            }
            $tr = M('transfer','n_','DB_CONFIG_DEV');
            $tw['bid'] = $data['url'];
            $tw['trtime'] = time();
            $tf = $tr->add($tw);
        }
        if (!empty($i) && !empty($ii) && !empty($tf)) {
            M()->commit();
            $this->success('添加书籍成功');
        } else {
            M()->rollback();
            $this->error('添加书籍失败，请重试');
        }
    }

    public function do_edit_book() {
        if (empty($_POST['tid']) || empty($_POST['title'])) {
            $this->error('内容提交不能为空');
        }
        $id = $_POST['id'];
        $t = M('type');
        $post = I('post.');
        $w['tid'] = $post['tid'];
        $w['title'] = $post['title'];
        $w['img'] = $post['img'];
        $w['content'] = $post['content'];
        $w['sex'] = $post['sex'];
        $w['num'] = $post['num'];
        $w['vip'] = $post['vip'];
        $w['state'] = $post['state'];

        $w['free_chapter'] = $post['free_chapter'] ? $post['free_chapter'] : 0;

        if (!empty($post['author'])) {
            $w['author'] = $post['author'];
        }
        if (!empty($post['free_days'])) {
            $w['free_days'] = $post['free_days'];
        }
        if (!empty($post['orderby'])) {
            $w['orderby'] = $post['orderby'];
        }
        $w['free_time'] = $post['free_time'];
        if (empty($post['free_time'])) {//书本免费，避免误操作，把其他数据清零
            $w['free_days'] = 0;
            $w['vip'] = 0;
        }

        $b = M('book');
        $i = $b->where(array('id' => $id))->save($w);
        if ($i > 0) {
            if (!empty($post['free_days'])) {
                $redis = redis(); //redis运用
                $redis->sADD('freedays', $_POST['id']);
            }
            $this->success('编辑书籍成功');
        } else {
            $this->error('编辑书籍失败，请重试');
        }
    }

    public function add_book_type() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $w = [];
        if (!empty($_GET['id'])) {
            $w['id'] = $_GET['id'];
            $t = M('type');
            $type = $t->where($w)->find();
            $this->assign('type', $type);
        }


        $this->display();
    }

    public function do_add_book_type() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if (empty($_POST['name'])) {
            $this->error('分类名称不可为空');
        }
        if (empty($_POST['sex'])) {
            $this->error('请选择性别类型');
        }
        if (empty($_POST['cover'])) {
            $this->error('请上传分类图片');
        }
        $t = M('type');
        $w['name'] = $_POST['name'];
        $w['sex'] = $_POST['sex'];
        $w['cover'] = $_POST['cover'];
        $w['closed'] = $_POST['closed'];
        if (!empty($_POST['id'])) {
            $w['id'] = $_POST['id'];
            $i = $t->save($w);
            $this->success('修改书籍分类成功');
        } else {
            $i = $t->add($w);
            $this->success('添加书籍分类成功');
        }
    }

    public function book_type() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $type = D('Type')->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function add_book_info() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $params = $this->params();
        if (!empty($params['id'])) {
            $book = D('Book')
                    ->table('__BOOK__ AS b')
//            ->join('__TYPE__ AS t on b.tid = t.id')
                    ->where("b.id = {$params['id']}")
                    ->find();
            $this->assign('book', $book);
        } else {
            $this->error('请先选择书籍', U('book_list'));
        }
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function edit_bookinfo() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
//        if ($admin['level'] > 0) {
//            $this->error('权限不足，无法使用此功能');
//        }
        $bi = M('bookinfo');
        $bookinfo = $bi->join('n_book ON n_book.id = n_bookinfo.bid', 'LEFT')->where(array('n_bookinfo.id' => $_GET['id']))->field('n_book.name,n_book.title,n_bookinfo.*')->find();
        $this->assign('bookinfo', $bookinfo);
        $this->display();
    }

    public function changebook() {
        $b = M('book');
        $book = $b->where(array('closed' => 1, 'tid' => $_GET['tid']))->select();
        if (!$book) {
            $book = 'error';
        }
        $this->ajaxReturn($book);
    }

    public function do_add_book_info() {
        $params = $this->params();
        foreach ($params as $key => $value) {
            if (empty($value)) {
                $this->error('所有数据不能为空');
            }
        }
        $number = trim($params['next_chapter_number']);
        $bi = M('bookinfo');
        $last = $bi->where(['bid' => $params['bid']])->order('number desc')->find();
        if($number>$last['number']){
            $result = true;
        }else{
            $result = $bi->where(['bid' => $params['bid'], 'number' => ['egt', $number]])->setInc('number');
        }
        
        if ($result) {
            $data = [
                'bid' => $params['bid'],
                'title2' => $params['title2'],
                'content' => stpstr($params['content']),
                'time' => time(),
                'number' => $number
            ];
            $i = $bi->add($data);
        }
        $this->success('添加成功', U('edit_bookinfo',['id' => $i]));
    }

    public function do_edit_bookinfo() {
        $params = $this->params();
        foreach ($params as $key => $value) {
            if (empty($value)) {
                $this->error('所有数据不能为空');
            }
        }
        $bi = M('bookinfo');
        $w['title2'] = $params['title2'];
        $w['content'] = stpstr($params['content']);
        $w['number'] = $params['number'];
        $i = $bi->where(array('id' => $params['id']))->save($w);
        if ($i > 0) {
            $this->success('编辑书籍章节成功');
        } else {
            $this->error('编辑书籍章节失败，请重试');
        }
    }

    public function book_list() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $page = I('get.page', 1);
        $pre_page = I('get.pre_page', 30);
        $b = M('book');
        if (!empty($_GET['sex'])) {
            $w['sex'] = $_GET['sex'];
        }
        if (!empty($_GET['keyword'])) {
            $keyword = trim($_GET['keyword']);
            $w['title|n_book.id'] = ['like', "%" . $keyword . "%"];
        }
        if (!empty($_GET['state'])) {
            $w['state'] = $_GET['state'];
        }
        if (!empty($_GET['tid'])) {
            $w['tid'] = $_GET['tid'];
        }
        $w['free_time'] = $_GET['free_time'] == 1 ? 1 : 0;
        $w['closed'] = $_GET['closed'] == 1 ? 1 : 0;
        $t = M('type');
        $type = $t->order("id asc")->select();
        $w['del_time'] = 0;
        $count = $b->where($w)->count();
        $Page = new \Think\Page($count, $pre_page);
        $show = $Page->show();
        $books = $b->where($w)->limit($Page->firstRow . ',' . $Page->listRows)->join('n_transfer ON n_transfer.bid = n_book.id', 'LEFT')->field('n_transfer.bid,n_transfer.trtime,n_book.*')->order('is_top desc')->select();
        $this->assign('type', $type);
        $this->assign('closed', $w['closed']);
        $this->assign('keyword', $_GET['keyword']);
        $this->assign('books', $books);
        $this->assign('page', $show);
        $this->display();
    }

    public function book_doshow() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['show'] == '1') {
            $w['show'] = 2;
        } else {
            $w['show'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改推荐状态成功');
        } else {
            $this->error('修改推荐状态失败，请重试');
        }
    }

    public function book_doeic() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['eic'] == '1') {
            $w['eic'] = 2;
        } else {
            $w['eic'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改编辑推荐状态成功');
        } else {
            $this->error('修改编辑推荐状态失败，请重试');
        }
    }

    public function is_top_book() {
        $b = M('book');
        $get = I('get.');
        if ($b->save($get)) {
            $this->success('修改编辑推荐状态成功');
        }
    }

    public function closed_book() {
        $b = M('book');
        $get = I('get.');
        if ($b->save($get)) {
            $this->success('修改编辑推荐状态成功');
        }
    }

    public function book_dohot() {
        $b = M('book');
        $book = $b->where(array('id' => $_GET['id']))->find();
        if ($book['hot'] == '1') {
            $w['hot'] = 2;
        } else {
            $w['hot'] = 1;
        }
        $i = $b->where(array('id' => $_GET['id']))->save($w);
        if ($i > 0) {
            $this->success('修改编辑推荐状态成功');
        } else {
            $this->error('修改编辑推荐状态失败，请重试');
        }
    }

    public function book_share() {
        $this->checklogin();
        $sequence = 'number asc';
        $ad = M('admin');
        $admin = $ad->where(array('id' => $_SESSION['aid']))->find();
        $this->assign('admin', $admin);
        $page = I('get.page', 1);
        $pre_page = I('get.pre_page', 100);
        $b = M('book');
        $bi = M('bookinfo');
        $w = array('bid' => $_GET['bid']);
        if (!empty($_GET['titlekeyword'])) {
            $w['number|title2'] =['like',"%".$_GET['titlekeyword']."%"];
        }
        if (!empty($_GET['sequence'])) {
            $sequence = 'number '.$_GET['sequence'];
        }
        $count = $bi->where($w)->count();
        $Page = new \Think\Page($count, $pre_page);
        $show = $Page->show();
        $book = $b->where(array('id' => $_GET['bid']))->find();
        $bookinfo = $bi->where($w)->order($sequence)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('book', $book);
        $this->assign('titlekeyword', $_GET['titlekeyword']);
        $this->assign('bookinfo', $bookinfo);
        $this->assign('page', $show);
        $this->display();
    }
    
    public function creatlinks() {
        //落地页域名
        if (empty(I('get.'))) {
            $this->ajaxReturn(false);
        }
        $data = I('get.');
        $wechat = D('Wechat')->find(1);
        $serurl = $wechat['serurl']; //跳转域名
        $jsurl = $wechat['jsurl']; //调用分享接口域名
        $pre_domin = md5(uniqid());
        $openurl = 'http://' . $pre_domin . '.' . $serurl . '/';
        $articleurl = 'http://' . $jsurl . "/Home/book/helloworld?id={$data['id']}";
        if(!empty($data['type'])){
            $articleurl = 'http://' . $jsurl . "/Home/book/helloworld/type/1/id/".$data['id'];
        }
        $durl = $openurl . 'home/book/share?url=' . urlencode($articleurl);
        $this->ajaxReturn($durl);
    }

    public function book_article() {
        $this->checklogin();
        $bi = M('bookinfo');
        $bookinfo = $bi->where(array('id' => $_GET['id']))->find();
        $number = $bookinfo['number'] + 1;
        $w['number'] = array('lt', $number);
        $w['bid'] = $bookinfo['bid'];
        $bookinfos = $bi->where($w)->select();
        foreach($bookinfos as &$v){
                $v['content']  = str_replace("&nbsp;&nbsp;&nbsp;&nbsp;", "<p/>", $v['content']);
            }
        $this->assign('bookinfos', $bookinfos);
        $nextbi = $bi->where(array('bid' => $bookinfo['bid'], 'number' => $number))->find();
        if (!$nextbi) {
            $this->error('下一章节不存在，无法生成文案');
        }
        $article = [];
        $article = D('article')->where(['bid'=>$bookinfo['bid']])->find();
        if(!empty($article)){
            $this->assign('article', $article);
        }
        $this->assign('url', $url);
        $this->assign('durl', $durl);
        $this->assign('id', $_GET['id']);
        $this->display("book_article_4");
    }
       
    public function add_book_txt() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        if ($admin['level'] > 0) {
            $this->error('权限不足，无法访问');
        }
        $t = M('type');
        $type = $t->select();
        $this->assign('type', $type);
        $this->display();
    }

    public function do_add_book_txt() {
//        $content = file_get_contents('Public/Uploads/book/5ca1dbcb20968.txt');
//            $array = explode("\r", $content);
//            pr($array);
        if (empty($_POST['tid']) || empty($_POST['title'])) {
            $this->error('内容提交不能为空');
        }
        $upload = new \Think\Upload();
        $upload->maxSize = 8388608;
        $upload->exts = array('jpg', 'png', 'jpeg', 'txt');
        $upload->rootPath = "./Public/Uploads/book/";
        $upload->savePath = '';
        $upload->autoSub = false;
        $upload->saveName = array('uniqid', '');
        $info = $upload->upload();
        if (!$info) {
            $this->error($upload->getError());
        }
        $t = M('type');
        $type = $t->where(array('id' => $_POST['tid']))->find();
        $w['name'] = $type['name'];
        $w['tid'] = $_POST['tid'];
        $w['title'] = $_POST['title'];
        $w['img'] = 1;
        $w['content'] = $_POST['content'];
        $w['sex'] = $_POST['sex'];
        $w['state'] = $_POST['state'];
        $w['closed'] = 1;
        $b = M('book');
        $i = $b->add($w);
        if ($i > 0) {
            $bi = M('bookinfo');
            $w2['tid'] = $_POST['tid'];
            $w2['bid'] = $i;
            $w2['time'] = time();
            $txt = $info['txt']['savename'];
//            $content = file_get_contents('Public/Uploads/book/' . $txt);
            $content = file_get_contents('Public/Uploads/book/5ca1dbcb20968.txt');
            $array = explode("###", $content);
            array_shift($array);
            $arr = array();
            foreach ($array as $k => $v) {
                $c = explode("\r\n", $v);
                $d = explode($c[0], $v);
                $d[0] = $c[0];
                array_push($arr, $d);
            }
            foreach ($arr as $k2 => &$v2) {
                $v2[1] = str_replace("\r\n", "</p><p>", $v2[1]);
                $v2[1] = substr($v2[1], 11);
                $v2[1] = substr($v2[1], 0, strlen($v2[1]) - 10);
            }
            foreach ($arr as $ka => $va) {
                $w2['title2'] = $va[0];
                $w2['content'] = $va[1];
                $w2['number'] = $ka + 1;
                $bi->add($w2);
            }
            $add_num = count($arr);
            $b = M('book');
            $b->where(array('id' => $i))->setInc('num', $add_num);
            die();
            unlink('Public/Uploads/book/' . $txt);
            $this->success('添加书籍成功');
        } else {
            $this->error('添加书籍失败，请重试');
        }
    }

    public function checklogin() {
        if (empty($_SESSION['aid'])) {
            $this->redirect('Login/login');
        }
    }

    public function checkadmin() {
        $ad = M('admin');
        $admin = $ad->where(array('id' => $_SESSION['aid']))->find();
        return $admin;
    }

    public function checkwechat() {
        $wc = M('wechat');
        $wechat = $wc->where(array('aid' => $_SESSION['aid']))->find();
        return $wechat;
    }

    public function del_book() {
        $n = M('book');

        $bookinfo = "bookinfo";

//        $nn=M($bookinfo);

        $pic = $n->where(array('id' => $_GET['id']))->find();

//       unlink('Public/Uploads/book/' . $pic['img']);

        $i = $n->where(array('id' => $_GET['id']))->setField('del_time', time());
        if ($i > 0) {
//             $ii = $nn->where(array('bid' => $_GET['id']))->delete();
            $this->success('删除成功', U('Book/book_list'));
        } else {
            $this->error('删除失败，请重试');
        }
    }

    public function del_bookinfo() {

        $bookinfo = "bookinfo";
        $n = M($bookinfo);

        $i = $n->where(array('id' => $_GET['id']))->delete();
        if ($i > 0) {
            $this->success('删除成功!', U('Book/book_share?bid=' . $_GET['bid']));
        } else {
            $this->error('删除失败，请重试');
        }
    }
    
    public function delall_bookinfo() {

        $bookinfo = "bookinfo";
        $book = "book";
        $n = M($bookinfo);
        $b = M($book);
        $i = $n->where(array('bid' => $_GET['id']))->delete();
        $a = $b->where(array('id' => $_GET['id']))->delete();
        if ($i > 0 && $a > 0) {
            $this->success('删除成功!', U('Book/book_list'));
        } 
        else {
            $this->error('删除失败，请重试', U('Book/book_list'));
        }
    }

    public function comment() {
        $this->checklogin();
        $admin = $this->checkadmin();
        $this->assign('admin', $admin);
        $page = I('get.page', 1);
        $pre_page = I('get.pre_page', 10);

        $CommentModel = D('BookComment');
        $count = $CommentModel->count();
        $Page = new \Think\Page($count, $pre_page);
        $show = $Page->show();

        $comment = $CommentModel
                ->order('add_time desc')
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->select();
        $this->assign('page', $show);
        $this->assign('comment', $comment);
        $this->display();
    }

    /*
     * $action  动作 add ,update, delete, select; update  
     * $model   对应模型   BookComment
     * $params  操作参数   comment_id:10|is_show:0
     * $url     跳转链接   Book|comment   控制器名|方法名
     */

    public function dowhat($action, $model, $params = '', $url = '') {
        $model = D($model);
        $params = explode('|', $params);
        $data = [];
        foreach ($params as $value) {
            $arr = explode(':', $value);
            $data[$arr[0]] = $arr[1];
        }
        if (!empty($url)) {
            $url = U(str_replace('|', '/', $url));
        } else {
            $url = $_SERVER['HTTP_REFERER'];
        }

        switch ($action) {
            case 'add':
                if ($model->add($data)) {
                    redirect($url, 1, '成功');
                }
                break;
            case 'update':

                if ($model->save($data)) {
                    redirect($url, 1, '成功');
                }

                break;
            case 'select':


                break;
            case 'delete':
                if ($model->where($data)->delete()) {
                    redirect($url, 1, '成功');
                }

                break;

            default:
                redirect($url, 1, '失败');
                break;
        }
        redirect($url, 1, '失败');
    }

    public function changeNumber($bid) {
        $sql = "SET @num = 0;UPDATE n_bookinfo SET number = (@num := @num + 1) WHERE bid = {$bid}";
        $result = D('Bookinfo')->comment('修正章节序号')->execute($sql);
        
        //章节总字数
        
        $this->success('成功', U('Book/book_share', ['bid' => $bid]));
    }

    public function downbook() {
        $data = $this->params();
        if (checkDomain($data['url'])) {
            //链接
        } else {
            //连接测试服务器
            $Book = M('Book','n_','DB_CONFIG_DEV'); 
            $Bookinfo = M('Bookinfo','n_','DB_CONFIG_DEV'); 
            //书id
            $bid = $data['url'];
            $book = $Book->field('title,tid,img,author,content,sex,state,source')->find($bid);
            $book['count'] = $Bookinfo->where(['bid' => $bid])->count();
            echo json_encode($book);
        }
    }
    
    
    public function getContent() {
        header("Content-type: text/html; charset=gbk");
       $input = $this->params();
       $data = $input['data'];
       if(empty($data['url'])){
           $data['code'] = '10001'; 
           $data['message'] = 'url不能为空'; 
           $this->ajaxReturn($data);
       }
       $url = $data['url'];
       $html = http_curl($url,'get','html');
       $html = mb_convert_encoding($html, 'utf-8','GB2312');
       $title = '/<h1>(.*)<\/h1>/is';
       preg_match($title,$html,$matches);
       $matches = array_reverse($matches);
       $data['title'] = $matches['0'];
       $content = '/<div id="content" name="content">(.*)<\/p><\/div>/is';
       preg_match($content,$html,$matches);
    }
    
    public function article() {
        $params = $this->params();
        $input = $params['data'];
        if(!empty($input) && count($input)>0){
            $article = M('article');
            $bookinfo = D('Bookinfo')->field('bid')->find($input['biid']);
            $data['title'] = $input['title'];
            $data['description'] = $input['description'];
            $data['cover'] = $input['cover'];
            $data['bid'] = $bookinfo['bid'];
            $data['add_time'] = time();
            $id = $article->add($data,['bid'=>$data['bid']],true);
            if($id){
                $this->response(1,'保存成功',['id'=>$id]);
            }else{
                $this->response(2,'保存失败');
            }
        }
    }
    
    public function updateCountword() {
        $data = $this->params();
        $content = D('Bookinfo')->where(['bid'=>$data['id']])->getField('content',TRUE);
        $totalnum = 0;
        foreach ($content as  $value) {
            $totalnum += count_word($value);
        }
        $totalnum = round($totalnum/10000,0);
        $re = D('Book')->setField(['id'=>$data['id'],'totalwords'=>$totalnum]);
        $this->success('修改成功', U('Book/edit_book',['id'=>$data['id']]));
    }
    
}
